
int STBY = 6;       /* STBY为正常工作/待机状态控制引脚 */

int AIN1 = 7;
int AIN2 = 8;
int PWMA = 10;

int BIN1 = 5;
int BIN2 = 4;
int PWMB = 9;

#define MOTOR_INDEX_A                   0     /* 电机A */
#define MOTOR_INDEX_B                   1     /* 电机B */
#define MOTOR_DIRECTION_CLOCKWISE       0     /* 顺时针 */
#define MOTOR_DIRECTION_ANTICLOCKWISE   1     /* 逆时针 */
#define MOTOR_DIRECTION_BRAKE           2     /* 刹车 */
#define MOTOR_DIRECTION_STOP            3     /* 自由停车 */

void motor_dir_set(int idx, int dir);

void setup()
{
  /* 设置引脚均为输出模式 */
  pinMode(STBY, OUTPUT);

  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(PWMA, OUTPUT);

  pinMode(BIN1, OUTPUT);
  pinMode(BIN2, OUTPUT);
  pinMode(PWMB, OUTPUT);

  /* 设置 TB6112 为正常工作模式 */
  digitalWrite(STBY, HIGH);

  motor_dir_set(MOTOR_INDEX_A, MOTOR_DIRECTION_BRAKE);
  motor_dir_set(MOTOR_INDEX_B, MOTOR_DIRECTION_BRAKE);

  analogWrite(PWMA, 128);
  analogWrite(PWMB, 128);
}

void loop()
{
  motor_dir_set(MOTOR_INDEX_A, MOTOR_DIRECTION_CLOCKWISE);
  motor_dir_set(MOTOR_INDEX_B, MOTOR_DIRECTION_ANTICLOCKWISE);
  delay(3000);

  motor_dir_set(MOTOR_INDEX_A, MOTOR_DIRECTION_BRAKE);
  motor_dir_set(MOTOR_INDEX_B, MOTOR_DIRECTION_BRAKE);
  delay(1000);

  motor_dir_set(MOTOR_INDEX_A, MOTOR_DIRECTION_ANTICLOCKWISE);
  motor_dir_set(MOTOR_INDEX_B, MOTOR_DIRECTION_CLOCKWISE);
  delay(3000);

  motor_dir_set(MOTOR_INDEX_A, MOTOR_DIRECTION_STOP);
  motor_dir_set(MOTOR_INDEX_B, MOTOR_DIRECTION_STOP);
  delay(1000);
}

void motor_dir_set(int idx, int dir)
{
  int IN1 = AIN1;
  int IN2 = AIN2;

  if (idx == MOTOR_INDEX_A)
  {
    IN1 = AIN1;
    IN2 = AIN2;
  }
  else if (idx == MOTOR_INDEX_B)
  {
    IN1 = BIN1;
    IN2 = BIN2;
  }
  else
  {
    return;
  }

  if (dir == MOTOR_DIRECTION_CLOCKWISE)
  {
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
  }

  if (dir == MOTOR_DIRECTION_ANTICLOCKWISE)
  {
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
  }

  if (dir == MOTOR_DIRECTION_BRAKE)
  {
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, HIGH);
  }

  if (dir == MOTOR_DIRECTION_STOP)
  {
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, LOW);
  }
}
